//
//  SLDownloadDataManager.m
//  Objective-C
//
//  Created by S_LINE on 2019/9/9.
//  Copyright © 2019 S_Line. All rights reserved.
//

#import "SLDownloadDataManager.h"

#import <FMDB/FMDB.h>
#import <YYKit/YYKit.h>

#import "SLLogger.h"

@interface SLDownloadDataManager ()

//@property (nonatomic, strong) FMDatabaseQueue *databaseQueue;
@property (nonatomic, strong) FMDatabase *database;

@end

@implementation SLDownloadDataManager

+ (instancetype)shareInstance {
    static SLDownloadDataManager *staticDownloadDataManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (staticDownloadDataManager == nil) {
            staticDownloadDataManager = [[SLDownloadDataManager alloc] init];
        }
    });
    
    return staticDownloadDataManager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self initSelf];
    }
    return self;
}

- (void)initSelf {
    [self initDB];
}

- (void)initDB {
    self.database = [FMDatabase databaseWithPath:[self getDownloadFileModelDatabasePath]];
    
    if ([self.database open]) {
        NSString *createTableSql = @"CREATE TABLE IF NOT EXISTS SLDownload (pid integer PRIMARY KEY AUTOINCREMENT,fileId text not null unique,showName text, fileName text,downloadUrl text,downloadState integer,progress float,resumeData BLOB)";
        [self.database executeStatements:createTableSql];
        
        [self.database close];
    }
    
//    self.databaseQueue = [[FMDatabaseQueue alloc] initWithPath:[self getDownloadFileModelDatabasePath]];
//    [self.databaseQueue inDatabase:^(FMDatabase * _Nonnull db) {
//        NSString *createTableSql = @"CREATE TABLE IF NOT EXISTS SLDownload (pid integer PRIMARY KEY AUTOINCREMENT,fileId text not null unique,showName text, fileName text,downloadUrl text,downloadState integer,progress float,resumeData BLOB)";
//        [db executeStatements:createTableSql];
//    }];
}

- (NSString *)getDownloadFileModelDatabasePath {
    NSString *documentPath = [self getDocumentPath];
    
    NSString *path = [documentPath stringByAppendingPathComponent:@"download.db"];
    
    return path;
}

- (NSString *)getDocumentPath {
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    return documentPath;
}

- (void)saveDownloadFileModel:(SLDownloadFileModel *)fileModel {
    
    SLDownloadFileModel *queryFileModel = [self queryDownloadFileModelDataWithFileId:fileModel.fileId];
    NSDictionary *dict = [self getAllKeysAndAllValuesWithFileModel:fileModel];

    BOOL __block result = NO;
    if ([queryFileModel isKindOfClass:[SLDownloadFileModel class]]) {
        NSString *updateSql = @"";
        
        for (int i = 0; i < dict.allKeys.count; i++) {
            NSString *keyString = [dict.allKeys objectAtIndex:i];
            if ([keyString isKindOfClass:[NSString class]] && keyString.length > 0) {
                id obj = [dict valueForKey:keyString];
                
                if (updateSql.length > 0) {
                    updateSql = [NSString stringWithFormat:@",%@=%@", keyString, obj];
                }
                else {
                    updateSql = [NSString stringWithFormat:@"%@=%@", keyString, obj];
                }
            }
        }
        
        if (updateSql.length > 0) {
            NSString *sql = [NSString stringWithFormat:@"update SLDownload set %@ where fileId == '%@'", updateSql, fileModel.fileId];
            
            if ([self.database open]) {
                NSString *updateSqlString = [self getUpdateSqlString];
                result = [self.database executeUpdate:updateSqlString, fileModel.fileId, fileModel.showName, fileModel.fileName, fileModel.downloadUrl, fileModel.downloadState, fileModel.progress, fileModel.resumeData, fileModel.fileId];
                
                if (result) {
                    [[SLLogger sharedInstance] addLog:[NSString stringWithFormat:@"下载任务更新成功 fileId:%@ - fileName:%@\n", fileModel.fileId, fileModel.showName]];
                }
                else {
                    [[SLLogger sharedInstance] addLog:[NSString stringWithFormat:@"下载任务更新失败 fileId:%@ - fileName:%@\n", fileModel.fileId, fileModel.showName]];
                }
                
                [self.database close];
            }
        }
    }
    else {
        
//        NSString *insertFileModelSql = [NSString stringWithFormat:@"insert into SLDownload (%@) VALUES (%@)", [dict valueForKey:kSLDownloadFileModelAllKeysKey], [dict valueForKey:kSLDownloadFileModelAllValuesKey]];
        
        if ([self.database open]) {
            NSString *insertString = [self getInsertSqlString];
            result = [self.database executeUpdate:insertString, fileModel.fileId, fileModel.showName, fileModel.fileName, fileModel.downloadUrl, fileModel.downloadState, fileModel.progress, fileModel.resumeData];
            
            if (result) {
                [[SLLogger sharedInstance] addLog:[NSString stringWithFormat:@"下载任务保存成功 fileId:%@ - fileName:%@\n", fileModel.fileId, fileModel.showName]];
            }
            else {
                [[SLLogger sharedInstance] addLog:[NSString stringWithFormat:@"下载任务保存失败 fileId:%@ - fileName:%@\n", fileModel.fileId, fileModel.showName]];
            }
            
            [self.database close];
        }
//        [self.databaseQueue inDatabase:^(FMDatabase * _Nonnull db) {
//            result = [db executeUpdate:insertFileModelSql];
//            NSLog(@"");
//        }];
        
//        BOOL __block result = NO;
//        [self.databaseQueue inDatabase:^(FMDatabase * _Nonnull db) {
//            result = [db executeUpdate:[self getInsertSqlString], fileModel.fileId, fileModel.showName, fileModel.fileName, fileModel.downloadUrl, fileModel.downloadState, fileModel.progress
//                      , fileModel.resumeData];
//        }];
        
        
    }
}

// 暂时没用
- (NSArray<NSString *> *)getAllKeys {
    return @[@"fileId", @"showName", @"fileName", @"downloadUrl", @"downloadState", @"progress", @"resumeData"];
}
- (NSString *)getInsertSqlString {
    NSString *firstString = @"insert into SLDownload(";
    NSString *middleString = @") values (";
    NSString *lastString = @")";
    
    NSArray *allKeys = [self getAllKeys];
    NSString *allKeysString = @"";
    NSString *allValuesString = @"";
    for (int i = 0; i < allKeys.count; i++) {
        NSString *keyString = [allKeys objectAtIndex:i];
        
        if (allKeysString.length == 0) {
            allKeysString = [NSString stringWithFormat:@"%@", keyString];
            allValuesString = @"?";
        }
        else {
            allKeysString = [NSString stringWithFormat:@"%@,%@", allKeysString, keyString];
            allValuesString = [NSString stringWithFormat:@"%@,?", allValuesString];
        }
    }
    return [NSString stringWithFormat:@"%@%@%@%@%@", firstString, allKeysString, middleString, allValuesString, lastString];
}

- (NSString *)getUpdateSqlString {
    
    NSArray *allKeys = [self getAllKeys];
    NSString *setKeyValueString = @"";
    for (int i = 0; i < allKeys.count; i++) {
        NSString *key = [allKeys objectAtIndex:i];
        
        if (setKeyValueString.length == 0) {
            setKeyValueString = [NSString stringWithFormat:@"%@=?", key];
        }
        else {
            setKeyValueString = [NSString stringWithFormat:@"%@,%@=?", setKeyValueString, key];
        }
    }
    
    NSString *updateSqlString = [NSString stringWithFormat:@"update SLDownload set %@ where fileId=?", setKeyValueString];
    
    return updateSqlString;
}

//static NSString *updateAllKVSql = @"fileId=%@, showName=%@, fileName=%@, downloadUrl=%@, downloadState=%@, progress=%@, resumeData=%@";
//- (NSString *)getUpdateSqlString {
//    return [NSString stringWithFormat:@"update SLDownload set %@", updateAllKVSql];
//}

static NSString *kSLDownloadFileModelAllKeysKey = @"kSLDownloadFileModelAllKeysKey";
static NSString *kSLDownloadFileModelAllValuesKey = @"kSLDownloadFileModelAllValuesKey";
- (NSDictionary *)getAllKeysAndAllValuesWithFileModel:(SLDownloadFileModel *)fileModel {
    NSString *allKeys = @"";
    NSString *allValues = @"";
    
    NSArray *allKeyList = [self getFileModelAllKeys];
    for (int i = 0; i < allKeyList.count; i++) {
        NSString *keyString = [allKeyList objectAtIndex:i];
        if ([keyString isKindOfClass:[NSString class]] && keyString.length > 0) {
            id valueObj = [fileModel valueForKey:keyString];
            
            NSString *valueString = [NSString stringWithFormat:@"%@", valueObj ? valueObj : @""];
            
            if (allKeys.length == 0) {
                allKeys = keyString;
            }
            else {
                allKeys = [NSString stringWithFormat:@"%@,%@", allKeys, keyString];
            }
            if (allValues.length == 0) {
                allValues = valueString;
            }
            else {
                allValues = [NSString stringWithFormat:@"%@,%@", allValues, valueString];
            }
        }
    }
    
    NSMutableDictionary *mutableDict = [NSMutableDictionary new];
    [mutableDict setObject:allKeys forKey:kSLDownloadFileModelAllKeysKey];
    [mutableDict setObject:allValues forKey:kSLDownloadFileModelAllValuesKey];
    
    return [mutableDict copy];
}

- (NSArray<NSString *> *)getFileModelAllKeys {
    return @[@"fileId", @"showName", @"fileName", @"downloadUrl", @"downloadState", @"progress", @"resumeData"];
}

#pragma mark - 查
- (SLDownloadFileModel *)queryDownloadFileModelDataWithFileId:(NSString *)fileId {
    NSString *querySql = [NSString stringWithFormat:@"select * from SLDownload where fileId = %@", fileId];
    
    __block SLDownloadFileModel *fileModel = nil;
    
    if ([self.database open]) {
        FMResultSet *resultSet = [self.database executeQuery:@"select * from SLDownload where fileId = ?", fileId];
        
        if (resultSet.next) {
            NSDictionary *dict = resultSet.resultDictionary;
            
            if ([dict isKindOfClass:[NSDictionary class]]) {
                SLDownloadFileModel *tempFileModel = [SLDownloadFileModel modelWithDictionary:dict];
                
                if ([tempFileModel isKindOfClass:[SLDownloadFileModel class]]) {
                    fileModel = tempFileModel;
                }
            }
        }
        
        [self.database close];
    }
//    [self.databaseQueue inDatabase:^(FMDatabase * _Nonnull db) {
//        FMResultSet *resultSet = [db executeQuery:querySql];
//
//        if (resultSet.next) {
//            NSDictionary *dict = resultSet.resultDictionary;
//
//            if ([dict isKindOfClass:[NSDictionary class]]) {
//                SLDownloadFileModel *tempFileModel = [SLDownloadFileModel modelWithDictionary:dict];
//
//                if ([tempFileModel isKindOfClass:[SLDownloadFileModel class]]) {
//                    fileModel = tempFileModel;
//                }
//            }
//        }
//    }];
    
    return fileModel;
}

- (NSArray<SLDownloadFileModel *> *)queryAllDatas {
    NSString *querySql = @"select * from SLDownload";
    
    __block NSMutableArray *fileModels = [NSMutableArray new];
    if ([self.database open]) {
        FMResultSet *resultSet = [self.database executeQuery:querySql];
        
        while (resultSet.next) {
            NSDictionary *dict = resultSet.resultDictionary;
            
            if ([dict isKindOfClass:[NSDictionary class]]) {
                SLDownloadFileModel *tempFileModel = [SLDownloadFileModel modelWithDictionary:dict];
                
                if ([tempFileModel isKindOfClass:[SLDownloadFileModel class]]) {
                    [fileModels addObject:tempFileModel];
                }
            }
        }
        [self.database close];
    }
//    [self.databaseQueue inDatabase:^(FMDatabase * _Nonnull db) {
//        FMResultSet *resultSet = [db executeQuery:querySql];
//
//        while (resultSet.next) {
//            NSDictionary *dict = resultSet.resultDictionary;
//
//            if ([dict isKindOfClass:[NSDictionary class]]) {
//                SLDownloadFileModel *tempFileModel = [SLDownloadFileModel modelWithDictionary:dict];
//
//                if ([tempFileModel isKindOfClass:[SLDownloadFileModel class]]) {
//                    [fileModels addObject:tempFileModel];
//                }
//            }
//        }
//    }];
    
    return fileModels;
}


@end
